package com.dayuanit.dy17.library.controller;

import com.dayuanit.dy17.library.dto.ResponseDTO;
import com.dayuanit.dy17.library.entity.Author;
import com.dayuanit.dy17.library.service.IAuthorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 加上Component标签，两个原因：1.并不是所有的类都能创建对象。 2.为创建的对象起一个别名。
 */
@Controller
public class AuthorController extends BaseController {

    @Autowired
    private IAuthorService authorService;

    public AuthorController() {
        System.out.println("-------AuthorController()-----");
    }

    @RequestMapping(value = "/author/queryAuthor.do")
    @ResponseBody
    public ResponseDTO queryAuthor(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String authorName = req.getParameter("authorName");

        try {
            Author author = authorService.queryAuthor(authorName);
            return ResponseDTO.success(author);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDTO.fail(e.getMessage());
        }
    }

    @RequestMapping(value = "/author/changeName.do")
    public ResponseDTO changeAuthorName(String oldName, String newName) {
        authorService.changeAuthorName(oldName, newName);
        return ResponseDTO.success();
    }
}
